<template>
  <el-drawer
      title="会话列表"
      v-model="localShowDrawer"
      direction="ltr"
      size="70%"
      :with-header="false"
  >
    <div class="drawer-content">
      <div class="close-button-container">
        <el-button @click="closeDrawer" type="text">
          <el-icon :size="24"><Fold /></el-icon>
        </el-button>
      </div>
      <!-- 使用传入的conversations数据 -->
<!--      <Conversations-->
<!--          v-model:active="activeConversationKey"-->
<!--          :items="conversations"-->
<!--          :label-max-width="200"-->
<!--          :show-tooltip="true"-->
<!--          row-key="key"-->
<!--          tooltip-placement="right"-->
<!--          :tooltip-offset="35"-->
<!--          show-to-top-btn-->
<!--          show-built-in-menu-->
<!--          @menu-command="handleMenuCommand"-->
<!--          @change="handleItemClick"-->
<!--      />-->
      <Conversations
          v-model:active="activeConversationKey"
          :items="conversations"
          :label-max-width="200"
          :show-tooltip="true"
          row-key="key"
          tooltip-placement="right"
          :tooltip-offset="35"
          show-to-top-btn
          show-built-in-menu
          @change="handleItemClick"
      />
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import type { ConversationItem, ConversationMenuCommand } from 'vue-element-plus-x/types/components/Conversations/types';
import {getChatMessages} from "@/api/inter";

// 定义props接收会话数据
const props = defineProps<{
  modelValue: boolean;
  conversations: ConversationItem[]; // 接收会话数据
}>();

const emit = defineEmits(['update:modelValue']);
const localShowDrawer = ref(props.modelValue);
const activeConversationKey = ref('');
const isLoading = ref(false);

// 转换接口返回的conversations格式（假设接口数据需要转换）
const conversations = ref<ConversationItem[]>([]);

// 监听conversations props变化
watch(
    () => props.conversations,
    (newConversations) => {
      if (newConversations) {
        // 转换接口数据为Conversations组件需要的格式
        const formattedConversations = newConversations.map(item => ({
          key: item.id,
          label: item.title,
          // 可添加更多字段如时间等
          createTime: item.createTime,
          // ...其他需要的字段
        }));
        conversations.value = formattedConversations;

        // 默认选中第一个会话
        if (formattedConversations.length > 0) {
          activeConversationKey.value = formattedConversations[0].key;
        }
      }
    },
    { deep: true }
);

// 内置菜单点击方法
function handleMenuCommand(command: ConversationMenuCommand, item: ConversationItem) {
  console.log('内置菜单点击事件：', command, item);
  uni.showToast({
    title: `操作: ${command}, 会话: ${item.label}`,
    icon: 'none'
  });

  // 删除会话逻辑
  if (command === 'delete') {
    const index = conversations.value.findIndex(i => i.key === item.key);
    if (index !== -1) {
      conversations.value.splice(index, 1);
      uni.showToast({ title: '删除成功', icon: 'success' });
    }
  }
  // 重命名会话逻辑
  if (command === 'rename') {
    item.label = '已修改';
    uni.showToast({ title: '重命名成功', icon: 'success' });
  }
}

// 监听Drawer显示状态
watch(
    () => props.modelValue,
    (newValue) => {
      localShowDrawer.value = newValue;
    }
);

watch(
    localShowDrawer,
    (newValue) => {
      emit('update:modelValue', newValue);
    }
);

const closeDrawer = () => {
  localShowDrawer.value = false;
};

const handleItemClick = async (item: ConversationItem) => {
  // 打印被点击的项
  console.log('被点击的会话项:', item);
  // 更新选中状态（可选）
  activeConversationKey.value = item.key;

  try {
    isLoading.value = true;

    // 请求聊天记录
    const response = await getChatMessages(item.key);

    // 打印聊天记录到控制台
    console.log('获取聊天记录成功:');
    console.log('会话ID:', item.id);
    console.log('聊天记录数量:', response.data?.length || 0);
    console.log('聊天记录详情:', response.data);
    uni.$emit('chatMessagesFetched', response.data);
    // 可在此处添加其他处理逻辑...

  } catch (error: any) {
    console.error('获取聊天记录失败:', error.message);
  } finally {
    isLoading.value = false;
    closeDrawer()
  }
};

</script>

<style scoped>
/* 样式保持不变 */
.drawer-content {
  position: relative;
  padding: 80rpx 0rpx 0rpx 0rpx;
}

.close-button-container {
  position: absolute;
  top: 10px;
  right: 10px;
}

.el-button {
  color: #888888;
  font-size: 24px;
}
</style>